﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Win32;
using System.IO;

namespace Blog.DbRepository
{
    public static class ContextFactory
    {
        private static string _blogConnectionString;
        private static string _applicationConnectionString;
        
        internal static DbDataContext CreateDataContext()
        {
            return new DbDataContext(new SqlConnection(BlogConnectionString));
        }

        private static string BuildDefaultConnectionString(string dbFileName)
        {
            FileInfo currentAssemblyLocation = new FileInfo(typeof(ContextFactory).Assembly.Location);
            string location = currentAssemblyLocation.Directory.Parent.Parent.FullName;

            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
            sb.AttachDBFilename = string.Format("{0}\\{1}", location, dbFileName);
            sb.PersistSecurityInfo = false;
            sb.IntegratedSecurity = true;
            sb.ConnectTimeout = 10;
            sb.WorkstationID = "(local)";
            sb.UserInstance = false;

            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL");
            if (key != null)
            {
                foreach (string s in key.GetValueNames())
                {
                    if (string.Compare(s, "MSSQLSERVER", true) == 0) //default (local) instance
                        sb.DataSource = ".";
                    else
                    {
                        sb.DataSource = string.Format(@".\{0}", s); //default (local)/SQLEXPRESS instance
                        sb.UserInstance = true;
                    }
                    
                    break;
                }
            }

            return sb.ToString();
        }

        public static string BlogConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_blogConnectionString))
                    _blogConnectionString = BuildDefaultConnectionString("DataBase\\BlogDb.mdf");

                return _blogConnectionString;
            }
            set
            {
                _blogConnectionString = value;
            }
        }

        public static string ApplicationConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_applicationConnectionString))
                    _applicationConnectionString = BuildDefaultConnectionString("DataBase\\BlogDb.mdf");

                return _applicationConnectionString;
            }
            set
            {
                _applicationConnectionString = value;
            }
        }
    }
}
